package com.ls.base.utils;

import org.apache.commons.lang.reflect.FieldUtils;

import java.lang.reflect.Field;

/**
 *
 * 字段属相相关的工具类，主要是包装了 <code> org.apache.commons.lang3.reflect.FieldUtils</code>方法,去掉了check exception
 * @author: xiaosu
 * @date: 2018-09-20  21:46
 */
public class FieldUtil {

    /**
     * 设置对象字段值
     * @param target
     * @param fieldName
     * @param value
     */
    public static void writeField(final Object target, final String fieldName, final Object value) {

        try {
            FieldUtils.writeField(target, fieldName, value, true);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 读取对象字段值
     * @param target
     * @return
     * @throws IllegalAccessException
     */
    public static Object readField(final Object target, final String fieldName) {
        try {
            return FieldUtils.readField(target, fieldName, true);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取对象字段属性
     * @param cls
     * @param fieldName
     * @return
     */
    public static Field getField(final Class<?> cls, final String fieldName) {
        return FieldUtils.getField(cls, fieldName, true);
    }
}
